<template>
	<el-container class="home-page">
		<el-aside width="70px" class="navi-bar" >
			<div class="user-head-image">
				<head-image :name="$store.state.userStore.userInfo.nickName"
					:url="$store.state.userStore.userInfo.headImageThumb" :size="46"
					@click.native="showSettingDialog = false">
				</head-image>
			</div>
			<el-menu  style="margin-top: 25px;">
				<el-menu-item title="消息"  >
					<router-link class="link" v-bind:to="'/home/chat'">
						<i class="icon iconfont icon-chat"></i>
						<span >消息</span>
						<div v-show="unreadCount > 0" class="unread-text">{{ unreadCount }}</div>
					</router-link>
				</el-menu-item>
				<el-menu-item title="通讯录">
					<router-link class="link" v-bind:to="'/home/friend'">
						<i class="icon iconfont icon-friend"></i>
						<span >通讯录</span>
					</router-link>
				</el-menu-item>
				<el-menu-item title="群组">
					<router-link class="link" v-bind:to="'/home/group'">
						<i class="icon iconfont icon-group"></i>
						<span >群组</span>
					</router-link>
				</el-menu-item>
                <!-- exe 专用-->
                <el-menu-item title="会议" @click="exeCreateConference" id="menu-item-1" >
                    <router-link class="link" v-bind:to="'/home/createmeeet'">
                        <i class="icon iconfont icon-chuangjianhuiyi"></i>
                        <span >会议</span>
                    </router-link>
                </el-menu-item>

                <!-- web 专用-->
				<!--<el-menu-item title="创建会议"  v-if="createIf" @click="createConference" id="menu-item-1" >
					<router-link class="link" v-bind:to="'/home/createmeeet'">
					<i class="icon iconfont icon-chuangjianhuiyi"></i>
					<span >创建会议</span>
				    </router-link>
                </el-menu-item>

				<el-menu-item title="加入会议">
					<router-link class="link" v-bind:to="'/home/joinmeeet'" @click.native="joinMeet" id="menu-item-2">
					<i class="icon iconfont icon-jiaruhuiyi"></i>
					<span >加入会议</span>
				    </router-link>
                </el-menu-item>-->
			</el-menu>
			<div class="exit-box" @click="onExit()" title="退出">
				<span class="icon iconfont icon-exit"></span>
			</div>
		</el-aside>
		<el-main class="content-box">
			<router-view></router-view>
		</el-main>
		<setting :visible="showSettingDialog" @close="closeSetting()"></setting>
		<user-info v-show="uiStore.userInfo.show" :pos="uiStore.userInfo.pos" :user="uiStore.userInfo.user" :adminSet="uiStore.userInfo.adminSet" :cancle-admin="uiStore.userInfo.cancleAdmin"
			@close="$store.commit('closeUserInfoBox')"></user-info>
		<full-image :visible="uiStore.fullImage.show" :url="uiStore.fullImage.url"
			@close="$store.commit('closeFullImageBox')"></full-image>
		<rtc-private-video ref="rtcPrivateVideo"></rtc-private-video>
		<rtc-group-video ref="rtcGroupVideo"></rtc-group-video>
	</el-container>
</template>

<script>
	import HeadImage from '../components/common/HeadImage.vue';
	import Setting from '../components/setting/Setting.vue';
	import UserInfo from '../components/common/UserInfo.vue';
	import FullImage from '../components/common/FullImage.vue';
	import RtcPrivateVideo from '../components/rtc/RtcPrivateVideo.vue';
	import RtcPrivateAcceptor from '../components/rtc/RtcPrivateAcceptor.vue';
	import RtcGroupVideo from '../components/rtc/RtcGroupVideo.vue';

	export default {
		components: {
			HeadImage,
			Setting,
			UserInfo,
			FullImage,
			RtcPrivateVideo,
			RtcPrivateAcceptor,
			RtcGroupVideo
		},
		data() {
			return {
                createIf:false,//是否创建会议
                showSettingDialog: false,
				lastPlayAudioTime: new Date().getTime() - 1000
			}
		},
		methods: {
			init() {

				this.$eventBus.$on('openPrivateVideo', (rctInfo) => {
					// 进入单人视频通话
					this.$refs.rtcPrivateVideo.open(rctInfo);
				});
				this.$eventBus.$on('openGroupVideo', (rctInfo) => {
					// 进入多人视频通话
					this.$refs.rtcGroupVideo.open(rctInfo);
				});

        this.$store.dispatch("load").then(() => {
          const isDevelopment = process.env.NODE_ENV !== 'production';
          const url = new URL(window.location.href);
          console.log("捕获到的地址："+url.toString())
            console.log("isDevelopment："+isDevelopment)
          const wsProtocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
          const wsUrl = wsProtocol + '//' + url.host + process.env.VUE_APP_WS_URL;
          if (isDevelopment) {
            this.$wsApi.connect(process.env.VUE_APP_WS_URL, sessionStorage.getItem("accessToken"));
          } else {

            console.log("wssUrl:" + wsUrl)
            // ws初始化
            this.$wsApi.connect(wsUrl, sessionStorage.getItem("accessToken"));
          }


          this.$wsApi.onConnect(() => {
            // 加载离线消息
            this.pullPrivateOfflineMessage(this.$store.state.chatStore.privateMsgMaxId);
            this.pullGroupOfflineMessage(this.$store.state.chatStore.groupMsgMaxId);
          });
					this.$wsApi.onMessage((cmd, msgInfo) => {
						if (cmd == 2) {
							// 关闭ws
							this.$wsApi.close(3000)
							// 异地登录，强制下线
							this.$alert("您已在其他地方登录，将被强制下线", "强制下线通知", {
								confirmButtonText: '确定',
								callback: action => {
									//location.href = "/";
                                    //location.href = "/talkmeet";
                                    //location.href = " /exe/outside";  // /exe/外部使用
                                    location.href = " /exe/inside";  // /exe/内部使用

                                }
							});

						} else if (cmd == 3) {
						    if (msgInfo.sensitiveStatus == 1 ){//敏感信息
                                msgInfo.content = "<img title='禁止发送敏感信息！' width=\"18\" height=\"18\" src=\"\" alt=\"禁止发送敏感词汇！\"/>"+" "+msgInfo.content
                            }
                            // 插入私聊消息
							this.handlePrivateMessage(msgInfo);
						} else if (cmd == 4) {
                            if (msgInfo.sensitiveStatus == 1 ){//敏感信息
                                msgInfo.content = "<img title='禁止发送敏感信息！' width=\"18\" height=\"18\" src=\"\" alt=\"禁止发送敏感词汇！\"/>"+" "+msgInfo.content
                            }
							// 插入群聊消息
							this.handleGroupMessage(msgInfo);
						}
					});
					this.$wsApi.onClose((e) => {
						console.log(e);
						if (e.code != 3000) {
							// 断线重连
              this.$message.error("连接断开，正在尝试重新连接...");
              if (isDevelopment) {
                this.$wsApi.reconnect(process.env.VUE_APP_WS_URL, sessionStorage.getItem(
                    "accessToken"));
              }else{
                this.$wsApi.reconnect(wsUrl, sessionStorage.getItem(
                    "accessToken"));
              }

						}
					});
				}).catch((e) => {
					console.log("初始化失败", e);
				})
			},
			pullPrivateOfflineMessage(minId) {
				this.$http({
					url: "/message/private/pullOfflineMessage?minId=" + minId,
					method: 'get'
				});
			},
			pullGroupOfflineMessage(minId) {
				this.$http({
					url: "/message/group/pullOfflineMessage?minId=" + minId,
					method: 'get'
				});
			},
			handlePrivateMessage(msg) {
				// 消息加载标志
				if (msg.type == this.$enums.MESSAGE_TYPE.LOADING) {
					this.$store.commit("loadingPrivateMsg", JSON.parse(msg.content))
					return;
				}
				// 消息已读处理，清空已读数量
				if (msg.type == this.$enums.MESSAGE_TYPE.READED) {
					this.$store.commit("resetUnreadCount", {
						type: 'PRIVATE',
						targetId: msg.recvId
					})
					return;
				}
				// 消息回执处理,改消息状态为已读
				if (msg.type == this.$enums.MESSAGE_TYPE.RECEIPT) {
					this.$store.commit("readedMessage", {
						friendId: msg.sendId
					})
					return;
				}
				// 标记这条消息是不是自己发的
				msg.selfSend = msg.sendId == this.$store.state.userStore.userInfo.id;
				// 单人webrtc 信令
				if (this.$msgType.isRtcPrivate(msg.type)) {
					this.$refs.rtcPrivateVideo.onRTCMessage(msg)
					return;
				}
				// 好友id
				let friendId = msg.selfSend ? msg.recvId : msg.sendId;
				this.loadFriendInfo(friendId).then((friend) => {
					this.insertPrivateMessage(friend, msg);
				})
			},
			insertPrivateMessage(friend, msg) {

				let chatInfo = {
					type: 'PRIVATE',
					targetId: friend.id,
					showName: friend.nickName,
					headImage: friend.headImage
				};
				// 打开会话
				this.$store.commit("openChat", chatInfo);
				// 插入消息
				this.$store.commit("insertMessage", msg);
				// 播放提示音
				if (!msg.selfSend && this.$msgType.isNormal(msg.type) &&
					msg.status != this.$enums.MESSAGE_STATUS.READED) {
					this.playAudioTip();
				}
			},
			handleGroupMessage(msg) {
				// 消息加载标志
				if (msg.type == this.$enums.MESSAGE_TYPE.LOADING) {
					this.$store.commit("loadingGroupMsg", JSON.parse(msg.content))
					return;
				}
				// 消息已读处理
				if (msg.type == this.$enums.MESSAGE_TYPE.READED) {
					// 我已读对方的消息，清空已读数量
					let chatInfo = {
						type: 'GROUP',
						targetId: msg.groupId
					}
					this.$store.commit("resetUnreadCount", chatInfo)
					return;
				}
				// 消息回执处理
				if (msg.type == this.$enums.MESSAGE_TYPE.RECEIPT) {
					// 更新消息已读人数
					let msgInfo = {
						id: msg.id,
						groupId: msg.groupId,
						readedCount: msg.readedCount,
						receiptOk: msg.receiptOk
					};
					this.$store.commit("updateMessage", msgInfo)
					return;
				}
				// 标记这条消息是不是自己发的
				msg.selfSend = msg.sendId == this.$store.state.userStore.userInfo.id;
				// 群视频信令
				if (this.$msgType.isRtcGroup(msg.type)) {
					this.$nextTick(() => {
						this.$refs.rtcGroupVideo.onRTCMessage(msg);
					})
					return;
				}
				this.loadGroupInfo(msg.groupId).then((group) => {
					// 插入群聊消息
					this.insertGroupMessage(group, msg);
				})
			},
			insertGroupMessage(group, msg) {

				let chatInfo = {
					type: 'GROUP',
					targetId: group.id,
					showName: group.remark,
					headImage: group.headImageThumb
				};
				// 打开会话
				this.$store.commit("openChat", chatInfo);
				// 插入消息
				this.$store.commit("insertMessage", msg);
				// 播放提示音
				if (!msg.selfSend && msg.type <= this.$enums.MESSAGE_TYPE.VIDEO &&
					msg.status != this.$enums.MESSAGE_STATUS.READED) {
					this.playAudioTip();
				}
			},
			onExit() {
				this.$wsApi.close(3000);
				sessionStorage.removeItem("accessToken");
				//location.href = "/";
                //location.href = "/talkmeet";
                //location.href = "/exe/outside";  // /exe/外部使用
                location.href = " /exe/inside";  // /exe/内部使用

            },
			playAudioTip() {
				if (new Date().getTime() - this.lastPlayAudioTime > 1000) {
					this.lastPlayAudioTime = new Date().getTime();
					let audio = new Audio();
					let url = require(`@/assets/audio/tip.wav`);
					audio.src = url;
					audio.play();
				}

			},
			showSetting() {
				this.showSettingDialog = true;
			},
			closeSetting() {
				this.showSettingDialog = false;
			},
			loadFriendInfo(id) {
				return new Promise((resolve, reject) => {
					let friend = this.$store.state.friendStore.friends.find((f) => f.id == id);
					if (friend) {
						resolve(friend);
					} else {
						this.$http({
							url: `/friend/find/${id}`,
							method: 'get'
						}).then((friend) => {
							this.$store.commit("addFriend", friend);
							resolve(friend)
						})
					}
				});
			},
			loadGroupInfo(id) {
				return new Promise((resolve, reject) => {
					let group = this.$store.state.groupStore.groups.find((g) => g.id == id);
					if (group) {
						resolve(group);
					} else {
						this.$http({
							url: `/group/find/${id}`,
							method: 'get'
						}).then((group) => {
							resolve(group)
							this.$store.commit("addGroup", group);
						})
					}
				});
			},
            //exe创建会议
            exeCreateConference(){
                console.log("exe版会议")
                //exe 会议专用、获取titile 内容document.title
                this.$elm.setTitleTip("create-meet");
                this.$elm.setTitleTip("");
                window.electronAPI.send("toMain","create-meet");
                //测试

            },//创建会议
            createConference(){
			    //web 会议专用
                console.log("web版会议")
                window.open('https://61.55.135.66:9443/');
                //exe 会议专用、获取titile 内容document.title
                /*this.$elm.setTitleTip("create-meet");
                this.$elm.setTitleTip("");*/
                //测试

            },//加入会议
            joinMeet(){
                setTimeout(() => {
                    // 这里是需要1秒后执行的代码
                    console.log('这里是需要延迟1秒执行的代码，防止出现闪屏');
                    this.$prompt('请输入会议号', '加入会议', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        inputPattern: /\S/,
                        inputErrorMessage: '请输入会议号'
                    }).then((o) => {
                        window.open('https://61.55.135.66:9443/'+o.value);
                    })
                }, 500);
            },
            //调用权限列表
            getPermission(){
                let array = sessionStorage.getItem("permissionList");
                const elementToCheck = "1020";
                // 使用includes方法判断 1010 创建群组 1020 创建会议
                this.createIf = array.includes(elementToCheck);
            }
		},
		computed: {
			uiStore() {
				return this.$store.state.uiStore;
			},
			unreadCount() {
				let unreadCount = 0;
				let chats = this.$store.state.chatStore.chats;
				chats.forEach((chat) => {
					unreadCount += chat.unreadCount
				});
				return unreadCount;
			}
		},
		watch: {
			unreadCount: {
				handler(newCount, oldCount) {
					let tip = newCount > 0 ? `${newCount}条未读` : "";
					this.$elm.setTitleTip(tip);
                    window.electronAPI.send("toMain",tip);
				},
				immediate: true
			}
		},
		mounted() {
		    //初始化数据
			this.init();
            //加载权限
            this.getPermission();
            //设置 现场民警可以设置为 群管理员的状态为false
            this.$store.commit("groupChat",false);
        },
		unmounted() {
			this.$wsApi.close();
		}
	}
</script>

<style scoped lang="scss">
	.navi-bar {
		background: #348cfa;
		padding: 8px;
		padding-top: 20px;
        border-right: 1px solid #e5e7eb;
		.el-menu {
			border: none;
			flex: 1;
			background:transparent;

			.el-menu-item {
				margin: 10px 0;
				background-color: #348cfa !important;
				padding: 0 !important;
				text-align: center;
				border-radius: 4px;

                span{
					line-height: 20px;
					font-size: 12px;
					 color: #F0F2F9;
				}
			    i{
					line-height: 20px;
					margin-top: 10px;
					margin-bottom: 3px;
					color: #F0F2F9;
				}
				.icon {
					font-size: 22px !important;
					color: #fff;
				}


				.link {
					display: flex;
					flex-direction: column;
					text-decoration: none;

					&.router-link-active .icon {
						color: #ffea14;
					}
					&.router-link-active span {
						color: #ffea14;

					}
				}


				.unread-text {
					position: absolute;
					line-height: 16px;
					background-color: #f56c6c;
					left: 30px;
					top: 9px;
					color: white;
					border-radius: 30px;
					padding: 0 3px;
					font-size: 9px;
					text-align: center;
					white-space: nowrap;
					border: none;
				}
			}
		}

		.exit-box {
			position: absolute;
			width: 50px;
			bottom: 20px;
			color: #fff;
			text-align: center;
			cursor: pointer;

			.icon {
				font-size: 24px;
			}

			&:hover {
				color: white;
			}
		}
	}

	.content-box {
		padding: 0;
		background-color: #fff;
		color: #344450;
		text-align: center;
	}
</style>
